package baseAPI;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import DataProcess.ServicePage;
import Stage.Stage1;
import baseClass.ServiceTable;
import javafx.application.Platform;

public class ReceiveHandler implements Runnable {

    Socket socket;
    Map<Integer, Socket> map;

    //用于存储整个数据包
    private volatile byte[] bytes=new byte[0];

    public ReceiveHandler() {
        super();
    }

    public ReceiveHandler(Map<Integer, Socket> map, Socket socket) {
        super();
        this.map = map;
        this.socket = socket;
    }

    /**
     */
    public void updateForConnect(int roomNumber,Socket socket) {
        Platform.runLater(()->{
            map.put(roomNumber,socket);
        });
    }

    /**
     * 断开客户端后，更新UI界面
     * 1.移除断开客户端的地址信息
     * 2.receivedMsgarea打印断开连接信息
     * 3.statusText更新成功连接个数
     * 4.移除map中对应的remoteSocketAddress
     */
    public void updateForDisConnect(String remoteSocketAddress) {
        Platform.runLater(()->{
            map.remove(remoteSocketAddress);
        });
    }

    @Override
    public void run() {
        String remoteSocketAddress = socket.getRemoteSocketAddress().toString().substring(1);
        try {
//            InputStream in = socket.getInputStream();
//            BufferedReader bReader = new BufferedReader(new InputStreamReader(in));
            //收消息
            String message;
            while(true) {
//                message = bReader.readLine();
                //获取输入流
                InputStream reader = socket.getInputStream();
                //此时bytes存储信息长度，字节未满四位表示存储不完全
                if (bytes.length < 4) {
                    //补全相应数据
                    byte[] head = new byte[4 - bytes.length];
                    int couter = reader.read(head);
                    if (couter < 0) {
                        continue;
                    }
                    //合并，bytes已达四节，判断counter是否为4来了解是否信息长度沾包
                    bytes = mergeByte(bytes, head, 0, couter);
                    if (couter < 4) {
                        continue;
                    }
                }
                //获取信息长度
                byte[] lengthMessage = new byte[0];
                lengthMessage = mergeByte(lengthMessage, bytes, 0, 4);
                int messageLength = Integer.parseInt(new String(lengthMessage));

                //数据包的信息尚未读取
                if (bytes.length - 4 < messageLength) {
                    byte[] body = new byte[messageLength + 4 - bytes.length];
                    int couter = reader.read(body);
                    if (couter < 0) {
                        continue;
                    }
                    //bytes存入整个数据
                    bytes = mergeByte(bytes, body, 0, couter);
                    if (couter < body.length) {
                        continue;
                    }
                }

                //读取长度信息后面的数据
                byte[] body = new byte[0];
                body = mergeByte(body, bytes, 4, bytes.length);
                bytes = new byte[0];

                message = new String(body);
                String[] messages = message.split("\\|\\|");

                if(messages[0].equals("bind")){
                    updateForConnect(Integer.parseInt(messages[1]),socket);
                }
                if(messages[0].equals("service")){
                    //判断是否有未处理的服务请求
                    try {
                        if (Stage1.database.select("*", "service", "roomNumber = " + messages[1] + " and service = " + messages[2]).next()) {
                            ServicePage.getServer().chooseClient(Integer.parseInt(messages[1]));
                            ServicePage.getServer().sendMessage("serviceRejected");//拒绝重复请求
                            continue;
                        }
                    }catch (SQLException ex){
                        System.out.println("returnServiceRejectionException");
                    }

                    if(Integer.parseInt(messages[2]) == 1){
                        MessageBox messageBox= new MessageBox("新服务订单", "注意刷新服务订单：早晨叫醒");
                    }
                    else if( Integer.parseInt(messages[2]) == 2) {
                        MessageBox messageBox = new MessageBox("新服务订单", "注意刷新服务订单：清洁服务");
                    }
                    ServicePage.inComingRequest(messages);
                }
                if(messages[0].equals("inquireDishes")){
                    ServicePage.sendDishes(messages[1]);
                }
                if(messages[0].equals("orderFinished")){
                    ServicePage.sendFoodFinished(messages[1]);
                }
                if(messages[0].equals("getOrders")){
                    ServicePage.sendOrders();
                }
            }
        } catch (IOException e) {
            updateForDisConnect(remoteSocketAddress);
        }
    }

    public byte[] mergeByte(byte[] a,byte[] b,int begin,int end){
        byte[] add=new byte[a.length+end-begin];
        int i=0;
        for(i=0;i<a.length;i++){
            add[i]=a[i];
        }
        for(int k=begin;k<end;k++,i++){
            add[i]=b[k];
        }
        return add;
    }
}




